
import hexSha1 from '@/utils/sha1.js'

var Crc16 = function (Data) {
  var CRC = 0xffff;
  var Tmp = 0;

  for (var i = 0; i < Data.length - 2; i++) {
    CRC = CRC ^ Data[i];
    for (var j = 0; j <= 7; j++) {
      Tmp = CRC & 1;
      CRC = CRC >> 1;
      if (Tmp != 0) {
        CRC = CRC ^ 0xA001;
      }
    }
  }
  if ((CRC >> 8) + ((CRC << 8) & 0xffff) <= 0xffff) {
    return (CRC >> 8) + ((CRC << 8) & 0xffff);
  }
  else {
    return ((CRC >> 8) + ((CRC << 8) & 0xffff)) - 0xffff;
  }
}
export function getSign(params, key) {
  //debugger
  let list = [],
    sign = '';
  let query = Object.assign({}, params)
  delete query.sign
  let keys = Object.keys(query).sort();
  for (var i = 0; i < keys.length; i++) {
    if (query[keys[i]] == null) {
      continue
    }
    if ((query[keys[i]] instanceof Array) && (query[keys[i]].length == 0) && (keys[i] == "status")) {
      continue
    }
    if ((query[keys[i]] instanceof Array) && (query[keys[i]].length == 1) && !(query[keys[i]][0]  instanceof Object)) {
      list.push(keys[i] + '=' + query[keys[i]])
    } else {
      list.push(keys[i] + '=' + ((query[keys[i]] instanceof Object) ? JSON.stringify(query[keys[i]]) : query[keys[i]]));
    }
  }
  let contentStr = list.join('&') + '&key=' + key;
  sign = hexSha1(contentStr).toLowerCase()
  contentStr = "签名串：" + contentStr + "\n签名结果：" + sign;
  //console.log(contentStr)
  return sign
}